/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package data;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Oriol
 */
public class UserController {

	private char _sep = File.separatorChar;
	private String _path;


	public UserController() {
//		String jarPath = System.getProperty("java.class.path");
//		int lastSlash = jarPath.lastIndexOf(_sep);
//		_path = jarPath.substring(0,lastSlash + 1);

       String jarPath = System.getProperty("java.class.path");
       int lastDot = jarPath.lastIndexOf(";");
       String aux = jarPath;
       if (lastDot != -1) {
            aux = jarPath.substring(0, lastDot);
       }
       int lastSlash = aux.lastIndexOf(_sep);
       _path = aux.substring(0,lastSlash + 1);
	}



	public void register(int userID, String username, String password) {
		boolean av = checkAvailavility(username);
		if(av) {
			FileControllerD _fc = new FileControllerD();
			BufferedWriter _output = _fc.getFileW(_path+"users.log");
			try {
				_output.append("id:" + userID + " username:" + username + " pass:" + password);
				_output.newLine();
				_output.close();
			} catch (IOException ex) {
				//Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
			}


			String user = userID+"";
			File aux = new File(_path+"users"+_sep+user);

			boolean b = aux.mkdir();

			File _file = new File(_path+"users"+_sep+user+_sep+"added.txt");
			try {
				b = _file.createNewFile();
			} catch (IOException ex) {
				Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
			}
            File _file2 = new File(_path+"users"+_sep+user+_sep+"usertraining.txt");
			try {
				b = _file2.createNewFile();
			} catch (IOException ex) {
				Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
			}
            File _file3 = new File(_path+"users"+_sep+user+_sep+"statistics.info");
			try {
				b = _file3.createNewFile();
				BufferedWriter _output3 = _fc.getFileW(_path+"users"+_sep+user+_sep+"statistics.info");
				_output3.write("tw:0");
				_output3.newLine();
				_output3.write("mw:0");
				_output3.newLine();
				_output3.write("nn:0");
				_output3.newLine();
				_output3.write("lr:0");
				_output3.newLine();
				_output3.write("lp:0");
				_output3.newLine();
				_output3.write("av:0");
				_output3.newLine();
				_output3.write("vm:0.0");
				_output3.newLine();
				_output3.close();				
			} catch (IOException ex) {
				Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
			}
			File _file4 = new File(_path+"users"+_sep+user+_sep+"user.pref");
			try {
				b = _file4.createNewFile();
				BufferedWriter _output2 = _fc.getFileW(_path+"users"+_sep+user+_sep+"user.pref");
               _output2.append("color:BLUE");
               _output2.newLine();
			   _output2.append("size:14");
               _output2.newLine();
			   _output2.append("ass:1");
               _output2.newLine();
			   _output2.append("N:6");
               _output2.newLine();
			   _output2.append("G:0");
               _output2.newLine();
			   _output2.append("S:5");
               _output2.newLine();
               _output2.close();
			} catch (IOException ex) {
				Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
			}

		}
	}

	public String getColor(int id) {
		String col = "BLUE";
		String user = id+"";
		FileControllerD fc = new FileControllerD();
		BufferedReader br = fc.getFileR(_path+"users"+_sep+user+_sep+"user.pref");
		try {
			String line = br.readLine();
			while(line != null) {
				if (line.contains("color:")) {
					col = line.substring(6);
				}
				line = br.readLine();
			}
		}
		catch(Exception e) {

		}
		try {
			br.close();
		} catch (IOException ex) {
			Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
		}
		return col;
	}

	public int getSize(int id) {
		int size = 14;
		String user = id+"";
		FileControllerD fc = new FileControllerD();
		BufferedReader br = fc.getFileR(_path+"users"+_sep+user+_sep+"user.pref");
		try {
			String line = br.readLine();
			while(line != null) {
				if (line.contains("size:")) {
					String aux = line.substring(5);
					size = Integer.parseInt(aux);
				}
				line = br.readLine();
			}
		}
		catch(Exception e) {

		}
		try {
			br.close();
		} catch (IOException ex) {
			Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
		}
		return size;
	}

	public void setColor(int id, String color) {
		try {
			String user = id+"";
			File inFile = new File(_path+"users"+_sep+user+_sep+"user.pref");

			if (!inFile.isFile()) {
				System.out.println("Parameter is not an existing file");
				return;
			}

			//Construct the new file that will later be renamed to the original filename.
			File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

			BufferedReader br = new BufferedReader(new FileReader(_path+"users"+_sep+user+_sep+"user.pref"));
			PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

			String line = null;

			  //Read from the original file and write to the new
			  //unless content matches data to be removed.
			while ((line = br.readLine()) != null) {

				if (line.trim().contains("color:")) {
					pw.println("color:"+color);
					pw.flush();
				}
				else {
					pw.println(line);
					pw.flush();
				}
			}
			pw.close();
			br.close();

			//Delete the original file
			if (!inFile.delete()) {
				System.out.println("Could not delete file");
				//return;
			}

			  //Rename the new file to the filename the original file had.
			if (!tempFile.renameTo(inFile))
				System.out.println("Could not rename file");

			}
			catch (FileNotFoundException ex) {
				ex.printStackTrace();
			}
			catch (IOException ex) {
				ex.printStackTrace();
			}

	}

	public void setSize(int id, int size) {
		try {
			String user = id+"";
			File inFile = new File(_path+"users"+_sep+user+_sep+"user.pref");

			if (!inFile.isFile()) {
				System.out.println("Parameter is not an existing file");
				return;
			}

			//Construct the new file that will later be renamed to the original filename.
			File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

			BufferedReader br = new BufferedReader(new FileReader(_path+"users"+_sep+user+_sep+"user.pref"));
			PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

			String line = null;

			  //Read from the original file and write to the new
			  //unless content matches data to be removed.
			while ((line = br.readLine()) != null) {

				if (line.trim().contains("size:")) {
					pw.println("size:"+size);
					pw.flush();
				}
				else {
					pw.println(line);
					pw.flush();
				}
			}
			pw.close();
			br.close();

			//Delete the original file
			if (!inFile.delete()) {
				System.out.println("Could not delete file");
				//return;
			}

			  //Rename the new file to the filename the original file had.
			if (!tempFile.renameTo(inFile))
				System.out.println("Could not rename file");

			}
			catch (FileNotFoundException ex) {
				ex.printStackTrace();
			}
			catch (IOException ex) {
				ex.printStackTrace();
			}
	}



	public boolean checkAvailavility(String username) {
		String _userField, _userName;
		FileControllerD _fc = new FileControllerD();
		BufferedReader _input = _fc.getFileR(_path+"users.log");
		try {
			String _userData = _input.readLine();
			while(_userData != null) {
				StringTokenizer user = new StringTokenizer(_userData);
				while(user.hasMoreTokens()) {
					_userField = user.nextToken();
					if(_userField.contains("username:")) {
						_userName = _userField.substring(9);
						if(_userName.equals(username)) return false;
					}
				}

				_userData = _input.readLine();
			}
            _input.close();



		}
		catch(Exception e) {

		}

		return true;
	}


	public void updateUser(int id, String username, String pass) {
		try {

			File inFile = new File(_path+"users.log");

			if (!inFile.isFile()) {
				System.out.println("Parameter is not an existing file");
				return;
			}

			//Construct the new file that will later be renamed to the original filename.
			File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

			BufferedReader br = new BufferedReader(new FileReader(_path+"users.log"));
			PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

			String line = null;

			  //Read from the original file and write to the new
			  //unless content matches data to be removed.
			while ((line = br.readLine()) != null) {

				if (line.trim().contains("id:"+id)) {
					pw.println("id:"+id+" username:"+username+" pass:"+pass);
					pw.flush();
				}
				else {
					pw.println(line);
					pw.flush();
				}
			}
			pw.close();
			br.close();

			//Delete the original file
			if (!inFile.delete()) {
				System.out.println("Could not delete file");
				//return;
			}

			  //Rename the new file to the filename the original file had.
			if (!tempFile.renameTo(inFile))
				System.out.println("Could not rename file");

			}
			catch (FileNotFoundException ex) {
				ex.printStackTrace();
			}
			catch (IOException ex) {
				ex.printStackTrace();
			}
	}


	public void deleteUser(int id) {
		String user = id+"";
		File carp = new File(_path+"users"+_sep+user);
		File ad = new File(_path+"users"+_sep+user+_sep+"added.txt");
		File ut = new File(_path+"users"+_sep+user+_sep+"usertraining.txt");
		File u = new File(_path+"users"+_sep+user+_sep+"user.pref");
		File s = new File(_path+"users"+_sep+user+_sep+"statistics.info");
		try {

			File inFile = new File(_path+"users.log");

			if (!inFile.isFile()) {
				System.out.println("Parameter is not an existing file");
				return;
			}

			//Construct the new file that will later be renamed to the original filename.
			File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

			BufferedReader br = new BufferedReader(new FileReader(_path+"users.log"));
			PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

			String line = null;

			  //Read from the original file and write to the new
			  //unless content matches data to be removed.
			while ((line = br.readLine()) != null) {

				if (!line.trim().contains("id:"+id)) {
					pw.println(line);
					pw.flush();
				}

			}
			pw.close();
			br.close();

			//Delete the original file
			if (!inFile.delete()) {
				System.out.println("Could not delete file");
				//return;
			}

			  //Rename the new file to the filename the original file had.
			if (!tempFile.renameTo(inFile))
				System.out.println("Could not rename file");

			}
			catch (FileNotFoundException ex) {
				ex.printStackTrace();
			}
			catch (IOException ex) {
				ex.printStackTrace();
			}
		
	}

	public void resetModel(int id) {
		String user = id+"";
		File add = new File(_path+"users"+_sep+user+_sep+"added.txt");
		add.delete();
		try {
			add.createNewFile();
		}
		catch(Exception e) {
			Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, e);
		}
		File train = new File(_path+"users"+_sep+user+_sep+"usertraining.txt");
		train.delete();
		try {
			train.createNewFile();
		}
		catch(Exception e) {
			Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, e);
		}

	}



	public int getNextID() {
		try {
			String _field;
			String _nextID;
			int res = 0;
			boolean _found = false;
			RandomAccessFile raf = new RandomAccessFile(_path  + "users.log", "rw");

			try {
				String _userData = raf.readLine();
				while (_userData != null && !_found) {
					StringTokenizer line = new StringTokenizer(_userData);
					while (line.hasMoreTokens()) {
						_field = line.nextToken();
						if (_field.contains("nextID:")) {
							long off = raf.getFilePointer();
							_nextID = _field.substring(7);
							res = Integer.parseInt(_nextID);
							//System.out.println(_field.length());
							//System.out.println(off);

							off = 7;
							//System.out.println(off);
							raf.seek(off);
							int a = res+1;
							String aux = String.valueOf(a);
							//System.out.print(aux);
							raf.writeBytes(aux);
							_found = true;
						}
					}
					_userData = raf.readLine();
				}
                raf.close();
			} catch (Exception e) {
			}
			return res;
		} catch (FileNotFoundException ex) {
			Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
		}
		return 0;
	}

 /**
    *
    *
    * Comprova que l'usuari existeix i retorna la seva id
    *
    * @author Oriol Caño
    * @param String name: Nom de l'usuari a cercar
    * @param String password: Contrasenya de l'usuari a cercar
    * @return retorna l'id de l'usuari amb el nom d'usuari name i la contrasenya pass,
  * si l'usuari no existeix retorna 0
    * @throws si hi ha un error retorna -1
    */
	public int checkLogin(String name, String pass) {
		String _userField, _userName, _passField, idField,_pass;
		int idAct = 0,res = 0;
		FileControllerD _fc = new FileControllerD();
		BufferedReader _input = _fc.getFileR(_path+"users.log");
		try {
			String _userData = _input.readLine();
			while(_userData != null) {
				StringTokenizer user = new StringTokenizer(_userData);
				while(user.hasMoreTokens()) {
					_userField = user.nextToken();
					if(_userField.contains("id:")) {
						idField = _userField.substring(3);
						idAct = Integer.parseInt(idField);
					}
					if(_userField.contains("username:")) {
						_userName = _userField.substring(9);
						if(_userName.equals(name)) {
							_passField = user.nextToken();
							_pass = _passField.substring(5);
							if(_pass.equals(pass)) {
								res = idAct;
							}

						}
					}

				}

				_userData = _input.readLine();
			}
            _input.close();



		}
		catch(Exception e) {
			return res = -1;
		}
        
		return res;
	}


	public BufferedReader getVerbs(int userID) {
		BufferedReader _aux;
		if(userID != 0)
		{
			String user = userID + "";
			FileControllerD _fc = new FileControllerD();
			_aux = _fc.getFileR(_path+"users"+_sep+user+_sep+"added.txt");
		}
		else {
			_aux = null;
		}
		
		

		return _aux;
	}


    public void initUserLog() {
          try {
            File aux = new File(_path+"users");
            if (!aux.exists()) {
                boolean b = aux.mkdir();
                FileControllerD _fc = new FileControllerD();
                BufferedWriter _output = _fc.getFileW(_path+"users.log");
               _output.append("nextID:1");
               _output.newLine();
               _output.close();
            }

       }
       catch(Exception e) {

        //Logger.getLogger(VerbDictionary.class.getName()).log(Level.SEVERE, null, e);
       }
    }









	public int getAssistant(int id) {
		int ass = 1;
		String user = id+"";
		FileControllerD fc = new FileControllerD();
		BufferedReader br = fc.getFileR(_path+"users"+_sep+user+_sep+"user.pref");
		try {
			String line = br.readLine();
			while(line != null) {
				if (line.contains("ass:")) {
					String aux = line.substring(4);
					ass = Integer.parseInt(aux);
				}
				line = br.readLine();
			}
		}
		catch(Exception e) {

		}
		try {
			br.close();
		} catch (IOException ex) {
			Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
		}
		return ass;
	}



	public void setAssistant(int id, int ass) {
		try {
			String user = id+"";
			File inFile = new File(_path+"users"+_sep+user+_sep+"user.pref");

			if (!inFile.isFile()) {
				System.out.println("Parameter is not an existing file");
				return;
			}

			//Construct the new file that will later be renamed to the original filename.
			File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

			BufferedReader br = new BufferedReader(new FileReader(_path+"users"+_sep+user+_sep+"user.pref"));
			PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

			String line = null;

			  //Read from the original file and write to the new
			  //unless content matches data to be removed.
			while ((line = br.readLine()) != null) {

				if (line.trim().contains("ass:")) {
					pw.println("ass:"+ass);
					pw.flush();
				}
				else {
					pw.println(line);
					pw.flush();
				}
			}
			pw.close();
			br.close();

			//Delete the original file
			if (!inFile.delete()) {
				System.out.println("Could not delete file");
				//return;
			}

			  //Rename the new file to the filename the original file had.
			if (!tempFile.renameTo(inFile))
				System.out.println("Could not rename file");

			}
			catch (FileNotFoundException ex) {
				ex.printStackTrace();
			}
			catch (IOException ex) {
				ex.printStackTrace();
			}
	}



	public int getN(int id) {
		int N = 6;
		String user = id+"";
		FileControllerD fc = new FileControllerD();
		BufferedReader br = fc.getFileR(_path+"users"+_sep+user+_sep+"user.pref");
		try {
			String line = br.readLine();
			while(line != null) {
				if (line.contains("N:")) {
					String aux = line.substring(2);
					N = Integer.parseInt(aux);
				}
				line = br.readLine();
			}
		}
		catch(Exception e) {

		}
		try {
			br.close();
		} catch (IOException ex) {
			Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
		}
		return N;
	}



	public float getG(int id) {
		float G = 0;
		String user = id+"";
		FileControllerD fc = new FileControllerD();
		BufferedReader br = fc.getFileR(_path+"users"+_sep+user+_sep+"user.pref");
		try {
			String line = br.readLine();
			while(line != null) {
				if (line.contains("G:")) {
					String aux = line.substring(2);
					G = Float.parseFloat(aux);
				}
				line = br.readLine();
			}
		}
		catch(Exception e) {

		}
		try {
			br.close();
		} catch (IOException ex) {
			Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
		}
		return G;
	}



	public int getS(int id) {
		int S = 5;
		String user = id+"";
		FileControllerD fc = new FileControllerD();
		BufferedReader br = fc.getFileR(_path+"users"+_sep+user+_sep+"user.pref");
		try {
			String line = br.readLine();
			while(line != null) {
				if (line.contains("S:")) {
					String aux = line.substring(2);
					S = Integer.parseInt(aux);
				}
				line = br.readLine();
			}
		}
		catch(Exception e) {

		}
		try {
			br.close();
		} catch (IOException ex) {
			Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
		}
		return S;
	}



	public void setN(int id, int N) {
		try {
			String user = id+"";
			File inFile = new File(_path+"users"+_sep+user+_sep+"user.pref");

			if (!inFile.isFile()) {
				System.out.println("Parameter is not an existing file");
				return;
			}

			//Construct the new file that will later be renamed to the original filename.
			File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

			BufferedReader br = new BufferedReader(new FileReader(_path+"users"+_sep+user+_sep+"user.pref"));
			PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

			String line = null;

			  //Read from the original file and write to the new
			  //unless content matches data to be removed.
			while ((line = br.readLine()) != null) {

				if (line.trim().contains("N:")) {
					pw.println("N:"+N);
					pw.flush();
				}
				else {
					pw.println(line);
					pw.flush();
				}
			}
			pw.close();
			br.close();

			//Delete the original file
			if (!inFile.delete()) {
				System.out.println("Could not delete file");
				//return;
			}

			  //Rename the new file to the filename the original file had.
			if (!tempFile.renameTo(inFile))
				System.out.println("Could not rename file");

			}
			catch (FileNotFoundException ex) {
				ex.printStackTrace();
			}
			catch (IOException ex) {
				ex.printStackTrace();
			}

	}



	public void setG(int id, float G) {
		try {
			String user = id+"";
			File inFile = new File(_path+"users"+_sep+user+_sep+"user.pref");

			if (!inFile.isFile()) {
				System.out.println("Parameter is not an existing file");
				return;
			}

			//Construct the new file that will later be renamed to the original filename.
			File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

			BufferedReader br = new BufferedReader(new FileReader(_path+"users"+_sep+user+_sep+"user.pref"));
			PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

			String line = null;

			  //Read from the original file and write to the new
			  //unless content matches data to be removed.
			while ((line = br.readLine()) != null) {

				if (line.trim().contains("G:")) {
					pw.println("G:"+G);
					pw.flush();
				}
				else {
					pw.println(line);
					pw.flush();
				}
			}
			pw.close();
			br.close();

			//Delete the original file
			if (!inFile.delete()) {
				System.out.println("Could not delete file");
				//return;
			}

			  //Rename the new file to the filename the original file had.
			if (!tempFile.renameTo(inFile))
				System.out.println("Could not rename file");

			}
			catch (FileNotFoundException ex) {
				ex.printStackTrace();
			}
			catch (IOException ex) {
				ex.printStackTrace();
			}

	}



	public void setS(int id, int S) {
		try {
			String user = id+"";
			File inFile = new File(_path+"users"+_sep+user+_sep+"user.pref");

			if (!inFile.isFile()) {
				System.out.println("Parameter is not an existing file");
				return;
			}

			//Construct the new file that will later be renamed to the original filename.
			File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

			BufferedReader br = new BufferedReader(new FileReader(_path+"users"+_sep+user+_sep+"user.pref"));
			PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

			String line = null;

			  //Read from the original file and write to the new
			  //unless content matches data to be removed.
			while ((line = br.readLine()) != null) {

				if (line.trim().contains("S:")) {
					pw.println("S:"+S);
					pw.flush();
				}
				else {
					pw.println(line);
					pw.flush();
				}
			}
			pw.close();
			br.close();

			//Delete the original file
			if (!inFile.delete()) {
				System.out.println("Could not delete file");
				//return;
			}

			  //Rename the new file to the filename the original file had.
			if (!tempFile.renameTo(inFile))
				System.out.println("Could not rename file");

			}
			catch (FileNotFoundException ex) {
				ex.printStackTrace();
			}
			catch (IOException ex) {
				ex.printStackTrace();
			}

	}

	public void addVerbToDict(String s, int _actualUser) {
		String user = _actualUser+"";
        FileControllerD _fc = new FileControllerD();
		BufferedWriter _output = _fc.getFileW(_path+"users"+_sep+user+_sep+"added.txt");
		try{
       _output.append(s);
       _output.newLine();
       _output.close();
		}
		catch(Exception e) {
			
		}
	}







	public static void main(String ar[]) {
		UserController u = new UserController();
		u.initUserLog();/*
		int id = u.getNextID();
		u.register(id, "Oriol", "123");
		u.setColor(id, "red");
		u.setSize(id, 25);*/



	}








	


	


}
